package com.ruyuan.controller;

import com.ruyuan.service.AdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author xx
 */
@Controller
@RequestMapping("/run")
public class RunController {

    @Autowired
    private AdminService adminService;

    @RequestMapping("/index")
    public String index() {
        return "run";
    }

    @RequestMapping("/add")
    public String add() {
        if (SecurityUtils.getSubject().isPermitted("run:add")) {
            return "runAdd";
        } else {
            return "unauthorized";
        }
    }

    @RequestMapping("/del")
    public String del() {
        if (SecurityUtils.getSubject().isPermitted("run:del")) {
            return "runDel";
        } else {
            return "unauthorized";
        }
    }

    @RequestMapping("/edit")
    public String edit() {
        if (SecurityUtils.getSubject().isPermitted("run:edit")) {
            return "runEdit";
        } else {
            return "unauthorized";
        }
    }

    @RequestMapping("/runAs")
    public String runAs(String userName) {
        if (adminService.queryByAdminName(userName) == null) {
            return "unauthorized";
        }
        //todo 检查一下能否切换用户身份
        Subject subject = SecurityUtils.getSubject();
        subject.runAs(new SimplePrincipalCollection(userName,
                subject.getPrincipals().getRealmNames().iterator().next()));
        return "run";
    }

    @RequestMapping("/runRelease")
    public String runRelease() {
        SecurityUtils.getSubject().releaseRunAs();
        return "run";
    }

}
